package com.sojson.config.filter;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.sojson.base.BaseFilter;
import com.sojson.config.filter.interfaces.impl.CustomParamDecryHttpServletRequestWrapper;
import com.sojson.util.filter.FilterUtil;

/**
 * 参数解密过滤器
 * 
 * @author liu
 * @date 2020-11-02
 */
public class ParameterDecryptionFilter extends OncePerRequestFilter implements BaseFilter {

    /** 不过滤的路径 */
    private HashSet<String> excludePath;

    /**
     * 把request转成自定义的CustomHttpServletRequestWrapper对参数进行处理(解密)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

        if (isExcludePath(excludePath) || !isHttpString(request)) {
            chain.doFilter(request, response);
            return;
        }

        chain.doFilter(new CustomParamDecryHttpServletRequestWrapper(request), response);
    }

    /**
     * 判断是否是字符串请求
     * 
     * @return
     */
    private boolean isHttpString(HttpServletRequest request) {
        return FilterUtil.isHttpString(request);
    }

    /**
     * 判断当前路径是否不过滤(过滤器无法设置不过滤哪些路径,要自己做)
     * 
     * @return
     */
    private boolean isExcludePath(HashSet<String> excludePath) {
        return FilterUtil.isExcludePath(excludePath);
    }

    /**
     * 获取不过滤的路径
     * 
     * @return
     */
    @Override
    public HashSet<String> getExcludePath() {
        return this.excludePath;
    }

    /**
     * 设置不过滤的路径
     * 
     * @param excludePath
     */
    @Override
    public void setExcludePath(HashSet<String> excludePath) {
        this.excludePath = excludePath;
    }

    /**
     * 获取当前过滤器的名字
     */
    @Override
    public String getName() {
        String name = "paramDecr";
        return name;
    }

}